import { defineStore } from 'pinia'
import { reactive, ref, watch, inject } from 'vue'
import { get_user_room_id_by_user_ids} from"@/api/chat/room"
export const ChatStore = defineStore('community', () => { 

    let chat_user_info = ref(undefined)   //注入一下,减少对用户仓库的多次注入用户信息
    
    let show_current_user_interact_box=ref(false) //使用全局,避免单独管理的交互交错问题
    let current_user_interact_box = ref(null)  //采用房间id做标记,减少对用户/群组的区分

    let current_chat = ref(null)       //采用房间id+type做标记 ,但是实际操作用的是current_chat_list
    let user_friends = ref([])
    let user_group = ref([])
    let current_chat_list =reactive({})
    let current_expand_model = ref(null)
    let room_unrend_lastmessage = reactive({ })
    let request_room_data = reactive({}) 
    let no_response_message = ref([])
    let room_message_meta = ref({})
    let current_show_info_room_info = ref(null)


    const get_current_chat = () => {
        return current_chat.value
    }
    const set_current_chat = (data) => {
        console.log(data)
        current_chat.value = data
    }   
    const get_friend_list= () => {
        return user_friends.value
    }
    const set_friend_list = (data) => { 
        user_friends.value = data
    }
    const pop_frined_list_item = (roomid) => {
        user_friends.value=user_friends.value.filter((i)=>i.room_info.room_id!=roomid)
    }

    const add_friend_item = (data) => {
        const middle_data = user_friends.value.filter((item) => {
            return item?.friend_info.id!=data?.friend_info?.id
        })
        user_friends.value = [...middle_data, data]
    }
    const get_friend_info_by_user_id = (id) => {
        
        return user_friends.value.filter((i) =>i.friend_info.id==id )[0]
    }
    const get_friend_info_by_room_id= (id) => {
        return user_friends.value.filter((i) =>i.room_info.room_id==id )[0]
    }
    const set_group_list = (data) => {
        user_group.value = data
    }
    const add_group_item = (data) => {
        user_group.value =[...user_group.value,data]
    }
    const pop_group_list_item = (roomid) => { 
        user_group.value=user_group.value.filter((i)=>i.room_info.room_id!=roomid)
    }
    
    const get_group_list= () => {
        return user_group.value
    }
    const get_group_info_by_room_id = (id) => {
        return user_group.value.filter((i) =>i.room_info.room_id==id)[0]
    }

    const add_current_chat_list = (room_id, value) => {
        current_chat_list[room_id]=value
    }
    
    const fix_current_chat_list_info_key = (room_id,key,value) => {
        current_chat_list[room_id][key] = value
    }
    const get_current_chat_list = () => {
        return  current_chat_list
    }
    const get_current_user_chat_info = (room_id) => {
        return current_chat_list[room_id]
    }
    const set_current_chat_list = (data) => {
        Object.assign(current_chat_list, data); // 保持响应式
    }
    const pop_current_chat_list_item = (roomid) => {
        const newData = { ...current_chat_list }; 
        delete newData[roomid]; 
        Object.assign(current_chat_list, newData);
      };

    const get_current_user_interact_box = () => {
        return current_user_interact_box.value
    }
    const set_current_user_interact_box = (data) => {
        current_user_interact_box.value = data
    }
    const set_user_info = (data) => {
        chat_user_info.value = data
    }
    const get_user_info = () => {
        return chat_user_info.value
    }
    const get_current_expand_model = () => {
        return current_expand_model.value
    }
    const set_current_expand_model = (data) => {
        current_expand_model.value = data
    }
    const get_room_unread_lastmessage_byroom_id = (room_id) => {
        if (room_id) { 
            return room_unrend_lastmessage[room_id]
        }
    }
    const fix_room_unread_lastmessage_byroom_id = (room_id,key,value) => { 
        room_unrend_lastmessage[room_id][key]=value
    }
    const pop_room_unrend_lastmessage_item = (roomid) => { 
        const newData = { ...room_unrend_lastmessage }; 
        delete newData[roomid]; 
        Object.assign(room_unrend_lastmessage, newData);
    }
    const get_request_room_data = () => {
        return request_room_data    
    }
    const set_request_room_data = (key,value) => { 
        return request_room_data[key]=value
    }
    const pop_request_room_data = (key) => { 
        request_room_data['data'] =request_room_data['data'].filter((item)=> item.room_id != key);
    }
    const set_no_response_message = (data) => { 
        no_response_message.value=data
    }
    const get_no_response_message = () => { 
        return no_response_message.value
    }
    const pop_no_response_message = (id) => { 
        no_response_message.value=no_response_message.value.filter((item)=> item.id != id);
    }
    const set_room_message_meta = (roomid,key, data) => { 
          room_message_meta[roomid] = room_message_meta[roomid] || {}
          room_message_meta[roomid][key]=data
    }
    const get_room_message_meta = (roomid) => { 
          return room_message_meta[roomid] || {}
    }
    const get_current_show_info_room_info = () => {
        return current_show_info_room_info.value
    }
    const set_current_show_info_room_info = (data) => {
        current_show_info_room_info.value = data
    }

    //经常使用,采用闭包
    const room_info_cache = inject('cacahe_room_info')
    const room_strem = inject('room_stream')
    const del_room_unread_lastmessage = async (room_id) => { 
        const data = await room_strem.getData(room_id)
        room_unrend_lastmessage[room_id] = {}
        room_unrend_lastmessage[room_id]['last_message'] = data?.last_message || 0
        room_unrend_lastmessage[room_id]['unread'] = data?.unread || 0
    }
    
    // 集中处理方法
    watch(
        () => Object.keys(current_chat_list), // 监听对象的所有一级键
        (newKeys, oldKeys) => {
            // console.log('一级键变化:', { newKeys, oldKeys });
            // 检测新增的一级键
            const addedKeys = newKeys.filter((key) => !oldKeys.includes(key));
            addedKeys.forEach(async (key) => {
                del_room_unread_lastmessage(current_chat_list[key]['room_info']?.room_id)
                // 执行缓存,仅仅缓存重要的,之后通过异步函数重新更新全部的信息
                if (current_chat_list[key]['room_info']?.type == 'double') {
                    // 存储double类型的所需信息
                    await room_info_cache.putData({
                        room_id: key,
                        type: 'double',
                        head_image: current_chat_list[key]['friend_info']?.head_image,
                        friend_info: current_chat_list[key]['friend_info']?.head_image,
                        username: current_chat_list[key]['friend_info']?.username,
                    })
                } else { 
                    // 存储group类型的所需信息
                    await room_info_cache.putData({
                        room_id: key,
                        type: 'group',
                        head_image: current_chat_list[key]['room_info']?.head_image,
                        group_name: current_chat_list[key]['room_info']?.group_name,
                    })
                }
            });
        }
    );
    const users_info_cache = inject('users_info_cache')
    watch(() => user_friends.value, async (newVal, oldVal) => {
        // 对于好友列表的信息采用缓存方案进行存储 
        newVal.forEach(async (item) => {
            const data = {...item.friend_info,'room_id':item.room_info.room_id}
            data['user_id'] = data['id']
            delete data['id']
            users_info_cache.putData({...data})
        })
        //这里应该执行过滤indexdb的信息
        //过滤非法好友存储,对于其他和好友相关采用try硬性删除
        if (newVal.length > oldVal.length) { 
            const roomchache = await room_info_cache.getAllData()
            const trueinfo = await get_user_room_id_by_user_ids(chat_user_info.value?.id)
            if (trueinfo != undefined && trueinfo.length!=0) { 
                roomchache.forEach((i) => {
                    const middle_ids = trueinfo.filter((id) => id == i.room_id)
                    if (middle_ids.length == 0) { 
                        room_info_cache.deleteData(i.room_id)
                        try { 
                            // 删除流信息
                            room_strem.deleteData(i.room_id)
                        }
                        catch { }
                    }
                 })
            }
        }
})
    

    
    return {
        room_message_meta,
        current_chat, user_group, current_chat_list, current_user_interact_box,
        show_current_user_interact_box,chat_user_info,no_response_message,
        user_friends,current_expand_model,room_unrend_lastmessage,request_room_data,
        set_user_info, get_user_info,fix_current_chat_list_info_key,
        get_current_chat,set_current_chat,
        get_friend_list,set_friend_list,add_friend_item,get_friend_info_by_room_id,get_friend_info_by_user_id,
        get_group_list,set_group_list,add_group_item,set_current_chat_list,get_group_info_by_room_id,
        add_current_chat_list, get_current_chat_list,get_current_user_chat_info,
        get_current_user_interact_box, set_current_user_interact_box,
        get_current_expand_model, set_current_expand_model,
        get_room_unread_lastmessage_byroom_id, fix_room_unread_lastmessage_byroom_id,
        get_request_room_data, set_request_room_data, pop_request_room_data,
        pop_group_list_item, pop_frined_list_item, pop_current_chat_list_item, pop_room_unrend_lastmessage_item,
        set_no_response_message, get_no_response_message, pop_no_response_message,
        set_room_message_meta, get_room_message_meta,
        set_current_show_info_room_info,get_current_show_info_room_info
        
        
    }
},
{
    persist: {
        enabled: true,
        strategies: [
            {   
                key: 'current_chat',
                storage: sessionStorage,
                paths: ['current_chat']
                
            },
            {
                key: 'user_friends',
                storage: sessionStorage,
                paths: ['user_friends']
            },
            {
                key: 'user_group',
                storage: sessionStorage,
                paths: ['user_group']
            },
            {
                key: 'current_chat_list',
                storage: sessionStorage,
                paths: ['current_chat_list']
            },
            {
                key: 'current_user_interact_box',
                storage: sessionStorage,
                paths: ['current_user_interact_box']
            }, {
                key: 'chat_user_info',
                storage: sessionStorage,
                paths: ['chat_user_info']
            }, {
                key: 'current_expand_model',
                storage: sessionStorage,
                paths: ['current_expand_model']
            },
            {
                key: 'room_unrend_lastmessage',
                storage: sessionStorage,
                paths:['room_unrend_lastmessage']
                
            }, {
                key: 'request_room_data',
                storage: sessionStorage,
                paths:['request_room_data']
            },
            {
                key: 'no_response_message',
                storage: sessionStorage,
                paths:['no_response_message']

            },
        ]
    }
}
)